package com.wulian.user.util;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.wulian.common.constants.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 *@Description:()
 * @author  caifulin
 * @date  2020/5/8 10:47
 * @version 1.0
 */
public class AliSms {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 功能描述: <br>
     * 〈发送短信验证码〉
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/5/8
     */
    public String sendSms(String phone) throws Exception {
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）

        //替换成你的AK
        final String accessKeyId = CommonConstants.ACCESSKEYID;//你的accessKeyId
        final String accessKeySecret = CommonConstants.ACCESSKEYSECRET;//你的accessKeySecret
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(CommonConstants.SIGNNAME);
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(CommonConstants.TEMPLATECODE);
        //随机产生一个6位数的验证码
        String random = (int) ((Math.random() * 9 + 1) * 100000) + "";
        //将生成的6位随机数存入Redis里(规则：key=手机号，value=验证码)，3分钟内有效
       /* Jedis jedis = JedisUtil.getJedisConn();
        jedis.set(phone, random);
        jedis.expire(phone, 300);*/
        redisTemplate.opsForValue().set(phone,random,CommonConstants.SMS_TIME_OUT, TimeUnit.SECONDS);
        //可选:模板中的变量替换JSON串
        //request.setTemplateParam(CommonConstants.TEMPLATEPARAM.replace("${code}", random));
        request.setTemplateParam(CommonConstants.TEMPLATECODE.replace("${code}", random));
        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (Exception e) {
            return "FAIL";
        } /*finally {
            if (jedis != null) {
                jedis.close();
            }
        }*/
        return sendSmsResponse.getCode();
    }
}